package com.globallogic.model;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

public class Tasks {
	
	private String messageBody;

	private void fillMessageBody(String fileName) {
		FileReader fileReader;
		BufferedReader bufferedReader;		
		String line;
		StringBuilder stringBuilder = new StringBuilder();		
		try {
			fileReader = new FileReader(fileName);
			bufferedReader = new BufferedReader(fileReader);
			while ((line = bufferedReader.readLine()) != null) {
				stringBuilder.append(line + "\n");
			}
			bufferedReader.close();
			fileReader.close();			
		} catch (FileNotFoundException e) {
			logger.error(e);
		} catch (IOException e) {
			logger.error(e);
		}
		messageBody = stringBuilder.toString();
	}
	
	public Tasks(){
		taskList = new ArrayList<Task>();
	}
	
	public Tasks(String fileName, String fileNameMessageBody){
        this();        
		loadFromFile(fileName, fileNameMessageBody);
	}	
	
	public void loadFromFile(String fileName, String fileNameMessageBody) {
		fillMessageBody(fileNameMessageBody);
		String line = null;
		FileReader fileReader = null;
		BufferedReader bufferedReader = null;
		taskList.clear();
		
		try {
			fileReader = new FileReader(fileName);
			bufferedReader = new BufferedReader(fileReader);
			
			do {
				line = bufferedReader.readLine();
				
				if (line != null) {
					taskList.add(createTaskFromLine(line, messageBody));					
				}
				
			} while (line != null);

			bufferedReader.close();
			
		} catch (FileNotFoundException e) {
			logger.error(e);
		} catch (IOException e) {
			logger.error(e);
		}
	}

	public List<Task> getTaskList() {
		return taskList;
	}
	
	private Task createTaskFromLine(String line, String messageBody) {
		
		Task task = new Task();
		String[] params;
		
		params = line.split(";");		
		
		task.project = params[0];
	    task.issueType = params[1];
	    task.summary = params[2];
	    task.reporter = params[3].toLowerCase();
	    task.description = messageBody;
	    task.cc = params[4];
	    task.location = params[5];
	    task.healthcareProgram = params[6];
	    task.medicalInsurance = params[7];
		
		return task;
	}
	
	private List<Task> taskList;
	private Logger logger = Logger.getLogger(Tasks.class);

}
